<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单管理 - 商家端</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
            font-family: 'Roboto', sans-serif;
            height: 100vh;
            min-height: 100vh;
            margin: 0;
        }
        .layout {
            display: flex;
            height: 100vh; /* 关键：撑满视口 */
        }
        .sidebar {
            width: 210px;
            height: 100vh; /* 关键：撑满视口 */
            background: #fff;
            box-shadow: 2px 0 16px rgba(0,0,0,0.07);
            display: flex;
            flex-direction: column;
            /* padding: 32px 0 0 0; 移除顶部padding */
            border-radius: 0; /* 去掉圆角 */
        }
        .sidebar-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #2d3a4b;
            text-align: center;
            margin-top: 32px; /* 用margin控制顶部间距 */
            margin-bottom: 36px;
        }
        .nav {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .nav a {
            display: block;
            padding: 12px 32px;
            color: #4a5a6a;
            text-decoration: none;
            font-size: 1.08rem;
            border-left: 4px solid transparent;
            transition: background 0.2s, color 0.2s, border-color 0.2s;
        }
        .nav a.active, .nav a:hover {
            background: #eaf3ff;
            color: #3478f6;
            border-left: 4px solid #7eb6ff;
        }
        .content {
            flex: 1;
            display: flex;
            align-items: flex-start;
            justify-content: center;
            padding: 48px 32px; /* 左右各32px边距 */
            overflow: auto;
        }
        .container {
            background: #fff;
            padding: 36px 28px 28px 28px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            width: 1200px;
            max-width: calc(100vw - 210px - 64px); /* 额外减去64px边距 */
        }
        .title {
            font-size: 1.7rem;
            font-weight: 700;
            color: #2d3a4b;
            margin-bottom: 24px;
            text-align: center;
        }
        .search-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            gap: 16px;
        }
        .search-controls {
            display: flex;
            gap: 12px;
            align-items: center;
        }
        .search-input {
            padding: 8px 12px;
            border: 1px solid #d1d9e6;
            border-radius: 6px;
            font-size: 0.95rem;
            outline: none;
            transition: border 0.2s;
            width: 200px;
        }
        .search-input:focus {
            border-color: #7eb6ff;
        }
        .search-btn, .reset-btn {
            padding: 8px 16px;
            border: 1px solid #d1d9e6;
            border-radius: 6px;
            background: #fff;
            color: #4a5a6a;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .search-btn:hover, .reset-btn:hover {
            background: #f5f8fa;
            border-color: #7eb6ff;
        }
        .table-container {
            max-height: calc(100vh - 300px);
            overflow-y: auto;
            border: 1px solid #e3e8ee;
            border-radius: 8px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px 8px;
            border-bottom: 1px solid #e3e8ee;
            text-align: center;
        }
        th {
            background: #f5f8fa;
            color: #4a5a6a;
            font-weight: 700;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .book-title {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: help;
        }
        .status-pending {
            color: #ff6b6b;
            font-weight: 600;
        }
        .status-shipped {
            color: #28a745;
            font-weight: 600;
        }
        .status-completed {
            color: #007bff;
            font-weight: 600;
        }
        .status-cancelled {
            color: #999;
            font-weight: 600;
            text-decoration: line-through;
        }
        .actions button {
            margin: 0 4px;
            padding: 6px 14px;
            border: none;
            border-radius: 6px;
            font-size: 0.9rem;
            cursor: pointer;
            color: #fff;
            transition: background 0.2s;
        }
        .actions button.ship { 
            background: #5eaefd; 
        }
        .actions button.ship:hover { 
            background: #4a9ce8; 
        }
        .actions button.view { 
            background: #6dd47e; 
        }
        .actions button.view:hover { 
            background: #5bc06d; 
        }
        .pagination {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 8px;
            margin-top: 18px;
            font-size: 15px;
        }
        .pagination button {
            padding: 6px 16px;
            border: none;
            border-radius: 4px;
            background: #f5f5f5;
            color: #3478f6;
            cursor: pointer;
            transition: background 0.2s, color 0.2s;
        }
        .pagination button:disabled {
            background: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
        }
        .pagination .page-info {
            margin: 0 8px;
            color: #333;
        }
        .pagination select {
            margin: 0 4px;
            padding: 4px 8px;
            border-radius: 4px;
            border: 1px solid #d1d9e6;
        }
        .page-size-selector {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .page-size-selector select {
            padding: 6px 8px;
            border: 1px solid #d1d9e6;
            border-radius: 4px;
            background: #fff;
            color: #4a5a6a;
        }
        .logout-btn {
            margin: 32px 24px 0 24px;
            padding: 12px 0;
            width: calc(100% - 48px);
            background: linear-gradient(90deg, #ff6b6b 0%, #ffb36b 100%);
            color: #fff;
            font-weight: 700;
            border: none;
            border-radius: 8px;
            font-size: 1.08rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .logout-btn:hover {
            background: linear-gradient(90deg, #ffb36b 0%, #ff6b6b 100%);
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 20px;
        }
        .error {
            color: #ff6b6b;
            text-align: center;
            padding: 20px;
        }
        /* 弹窗样式 */
        .modal-mask {
            position: fixed;
            left: 0; top: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.18);
            z-index: 1000;
            display: none;
            align-items: center;
            justify-content: center;
        }
        .modal-card {
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 12px 40px rgba(0,0,0,0.18);
            min-width: 420px;
            max-width: 98vw;
            padding: 38px 38px 28px 38px;
            position: relative;
            animation: fadeIn 0.2s;
        }
        .modal-title {
            font-size: 1.4rem;
            font-weight: 800;
            color: #2d3a4b;
            margin-bottom: 12px;
            letter-spacing: 1px;
            text-align: center;
        }
        .modal-divider {
            width: 100%;
            height: 1px;
            background: #e3e8ee;
            margin-bottom: 22px;
            border: none;
        }
        .modal-close {
            position: absolute;
            right: 18px;
            top: 18px;
            font-size: 1.3rem;
            color: #aaa;
            background: none;
            border: none;
            cursor: pointer;
        }
        .modal-row {
            display: flex;
            align-items: flex-start;
            margin-bottom: 18px;
        }
        .modal-label {
            width: 110px;
            color: #888;
            font-weight: 500;
            text-align: right;
            flex-shrink: 0;
            margin-right: 10px;
            letter-spacing: 1px;
        }
        .modal-value {
            color: #222;
            word-break: break-all;
            text-align: left;
            flex: 1;
        }
        .modal-value strong {
            font-weight: 700;
        }
        .modal-status-tag {
            display: inline-block;
            padding: 2px 12px;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 700;
            color: #fff;
            background: #ff6b6b;
        }
        .modal-status-tag.shipped { background: #28a745; }
        .modal-status-tag.completed { background: #007bff; }
        .modal-status-tag.cancelled { background: #999; }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
    <script type="module">
        import { API_BASE_URL } from './api_config.js';
        window.API_BASE_URL = API_BASE_URL;
    </script>
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="sidebar-title">商家中心</div>
            <nav class="nav">
                <a href="merchant_home.html">首页</a>
                <a href="merchant_books.html">书籍管理</a>
                <a href="merchant_orders.html" class="active">订单处理</a>
                <a href="merchant_add_book.html">发布新书</a>
                <a href="merchant_profile.html">个人信息</a>
            </nav>
            <button id="logoutBtn" class="logout-btn">退出登录</button>
        </aside>
        <main class="content">
            <div class="container">
                <div class="title">订单管理</div>
                
                <!-- 搜索区域 -->
                <div class="search-section">
                    <div class="search-controls">
                        <input type="text" id="bookNameSearch" class="search-input" placeholder="搜索书名...">
                        <input type="text" id="buyerNameSearch" class="search-input" placeholder="搜索买家姓名...">
                        <button id="searchBtn" class="search-btn">搜索</button>
                        <button id="resetBtn" class="reset-btn">重置</button>
                    </div>
                    <div class="page-size-selector">
                        <span>每页显示:</span>
                        <select id="pageSizeSelect">
                            <option value="5">5</option>
                            <option value="10" selected>10</option>
                            <option value="15">15</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </div>
                </div>

                <!-- 表格容器 -->
                <div class="table-container">
                    <table id="ordersTable">
                        <thead>
                            <tr>
                                <th>订单ID</th>
                                <th>书名</th>
                                <th>买家</th>
                                <th>数量</th>
                                <th>总价</th>
                                <th>状态</th>
                                <th>下单时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="ordersTableBody">
                            <!-- 动态生成订单数据 -->
                        </tbody>
                    </table>
                </div>

                <!-- 加载和错误消息 -->
                <div id="loadingMessage" class="loading" style="display: none;">正在加载订单数据...</div>
                <div id="errorMessage" class="error" style="display: none;"></div>

                <!-- 分页 -->
                <div class="pagination" id="pagination" style="display: none;">
                    <!-- 动态生成分页按钮 -->
                </div>
            </div>
        </main>
    </div>
    <!-- 弹窗区域 -->
    <div class="modal-mask" id="orderModalMask">
        <div class="modal-card">
            <button class="modal-close" id="orderModalClose">×</button>
            <div class="modal-title">订单详情</div>
            <hr class="modal-divider" />
            <div id="orderModalContent">
                <!-- 动态填充 -->
            </div>
        </div>
    </div>
    <script>
        // 登录校验和页面初始化
        (function() {
            // 检查登录状态
            var userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            var merchantId = userInfo.userId;
            if (!merchantId) {
                alert('未检测到商家身份，请重新登录');
                window.location.href = 'login.html';
                return;
            }

            // 获取API配置
            var apiBaseUrl = window.API_BASE_URL || 'http://localhost:3010';

            // 分页状态
            var currentPage = 1;
            var pageSize = 10;
            var totalPages = 0;
            var totalRecords = 0;

            // 搜索状态
            var bookName = '';
            var buyerName = '';

            // 加载订单数据
            function loadOrders() {
                showLoading();
                
                const params = new URLSearchParams({
                    pageNum: currentPage,
                    pageSize: pageSize,
                    merchantId: merchantId
                });
                
                if (bookName) params.append('bookName', bookName);
                if (buyerName) params.append('buyerName', buyerName);

                fetch(`${apiBaseUrl}/bookOrder/page?${params}`)
                    .then(response => response.json())
                    .then(data => {
                        hideLoading();
                        
                        if (data.success && data.code === 200) {
                            displayOrders(data.data);
                            updatePagination(data.data);
                        } else {
                            showError('加载订单失败: ' + (data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('加载订单失败:', error);
                        hideLoading();
                        showError('网络错误，请检查网络连接');
                    });
            }

            // 显示订单数据
            function displayOrders(data) {
                const tbody = document.getElementById('ordersTableBody');
                tbody.innerHTML = '';

                if (data.records && data.records.length > 0) {
                    data.records.forEach(order => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${order.id}</td>
                            <td class="book-title" title="${order.bookTitle}">${order.bookTitle}</td>
                            <td>${order.buyerName}</td>
                            <td>${order.quantity}</td>
                            <td>￥${order.totalPrice.toFixed(2)}</td>
                            <td class="status-${getStatusClass(order.status)}">${getStatusText(order.status)}</td>
                            <td>${formatDate(order.createdAt)}</td>
                            <td class="actions">
                                ${order.status === 0 ? '<button class="ship" onclick="shipOrder(' + order.id + ')">发货</button>' : ''}
                                <button class="view" onclick="viewOrder(${order.id})">查看</button>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                } else {
                    tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: #666;">暂无订单数据</td></tr>';
                }
            }

            // 获取状态样式类
            function getStatusClass(status) {
                switch (status) {
                    case 0: return 'pending';
                    case 1: return 'shipped';
                    case 2: return 'completed';
                    case 3: return 'cancelled';
                    default: return 'pending';
                }
            }

            // 获取状态文本
            function getStatusText(status) {
                switch (status) {
                    case 0: return '待发货';
                    case 1: return '已发货';
                    case 2: return '已完成';
                    case 3: return '已取消';
                    default: return '待发货';
                }
            }

            // 格式化日期
            function formatDate(dateString) {
                const date = new Date(dateString);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }

            // 更新分页
            function updatePagination(data) {
                const pagination = document.getElementById('pagination');
                totalPages = data.pages;
                totalRecords = data.total;

                if (totalPages <= 1) {
                    pagination.style.display = 'none';
                    return;
                }
                pagination.style.display = 'flex';
                pagination.innerHTML = '';

                // 上一页
                const prevBtn = document.createElement('button');
                prevBtn.textContent = '上一页';
                prevBtn.disabled = currentPage === 1;
                prevBtn.onclick = () => {
                    if (currentPage > 1) {
                        currentPage--;
                        loadOrders();
                    }
                };
                pagination.appendChild(prevBtn);

                // 页码信息
                const pageInfo = document.createElement('span');
                pageInfo.className = 'page-info';
                pageInfo.textContent = `第 ${currentPage} / ${totalPages} 页`;
                pagination.appendChild(pageInfo);

                // 下一页
                const nextBtn = document.createElement('button');
                nextBtn.textContent = '下一页';
                nextBtn.disabled = currentPage === totalPages;
                nextBtn.onclick = () => {
                    if (currentPage < totalPages) {
                        currentPage++;
                        loadOrders();
                    }
                };
                pagination.appendChild(nextBtn);

                // 每页显示
                const pageSizeLabel = document.createElement('span');
                pageSizeLabel.textContent = '每页显示:';
                pageSizeLabel.style.marginLeft = '12px';
                pagination.appendChild(pageSizeLabel);

                const pageSizeSelect = document.createElement('select');
                [5, 10, 15, 20, 50].forEach(size => {
                    const option = document.createElement('option');
                    option.value = size;
                    option.textContent = size;
                    if (size === pageSize) option.selected = true;
                    pageSizeSelect.appendChild(option);
                });
                pageSizeSelect.onchange = function() {
                    pageSize = parseInt(this.value);
                    currentPage = 1;
                    loadOrders();
                };
                pagination.appendChild(pageSizeSelect);

                const pageSizeUnit = document.createElement('span');
                pageSizeUnit.textContent = '条';
                pagination.appendChild(pageSizeUnit);
            }

            // 显示加载状态
            function showLoading() {
                document.getElementById('loadingMessage').style.display = 'block';
                document.getElementById('errorMessage').style.display = 'none';
                document.getElementById('ordersTable').style.display = 'none';
                document.getElementById('pagination').style.display = 'none';
            }

            // 隐藏加载状态
            function hideLoading() {
                document.getElementById('loadingMessage').style.display = 'none';
                document.getElementById('ordersTable').style.display = 'table';
            }

            // 显示错误消息
            function showError(message) {
                document.getElementById('errorMessage').textContent = message;
                document.getElementById('errorMessage').style.display = 'block';
                document.getElementById('ordersTable').style.display = 'none';
                document.getElementById('pagination').style.display = 'none';
            }

            // 搜索功能
            document.getElementById('searchBtn').addEventListener('click', function() {
                bookName = document.getElementById('bookNameSearch').value.trim();
                buyerName = document.getElementById('buyerNameSearch').value.trim();
                currentPage = 1;
                loadOrders();
            });

            // 重置功能
            document.getElementById('resetBtn').addEventListener('click', function() {
                document.getElementById('bookNameSearch').value = '';
                document.getElementById('buyerNameSearch').value = '';
                bookName = '';
                buyerName = '';
                currentPage = 1;
                loadOrders();
            });

            // 回车搜索
            document.getElementById('bookNameSearch').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('searchBtn').click();
                }
            });

            document.getElementById('buyerNameSearch').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('searchBtn').click();
                }
            });

            // 页面大小改变
            document.getElementById('pageSizeSelect').addEventListener('change', function() {
                pageSize = parseInt(this.value);
                currentPage = 1;
                loadOrders();
            });

            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', function() {
                localStorage.removeItem('userInfo');
                window.location.href = 'login.html';
            });

            // 发货功能
            window.shipOrder = function(orderId) {
                if (confirm('确认发货此订单？')) {
                    const apiBaseUrl = window.API_BASE_URL || 'http://localhost:3010';
                    fetch(`${apiBaseUrl}/bookOrder`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id: orderId, status: 1 })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('发货成功！');
                            loadOrders();
                        } else {
                            alert('发货失败: ' + (data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        alert('发货请求失败，请检查网络连接');
                    });
                }
            };

            // 查看订单详情
            window.viewOrder = function(orderId) {
                const mask = document.getElementById('orderModalMask');
                const content = document.getElementById('orderModalContent');
                content.innerHTML = '<div style="text-align:center;color:#888;">加载中...</div>';
                mask.style.display = 'flex';
                const apiBaseUrl = window.API_BASE_URL || 'http://localhost:3010';
                fetch(`${apiBaseUrl}/bookOrder/${orderId}`)
                    .then(res => res.json())
                    .then(data => {
                        if (data.success && data.code === 200) {
                            const order = data.data;
                            let statusText = getStatusText(order.status);
                            let statusClass = getStatusClass(order.status);
                            let createdAt = formatDate(order.createdAt);
                            let timeRow = '';
                            let timeLabel = '';
                            if (order.status === 1) {
                                timeLabel = '发货时间';
                                timeRow = `<div class=\"modal-row\"><span class=\"modal-label\">${timeLabel}：</span><span class=\"modal-value\">${formatDate(order.updatedAt)}</span></div>`;
                            } else if (order.status === 2) {
                                timeLabel = '签收时间';
                                timeRow = `<div class=\"modal-row\"><span class=\"modal-label\">${timeLabel}：</span><span class=\"modal-value\">${formatDate(order.updatedAt)}</span></div>`;
                            } else if (order.status === 3) {
                                timeLabel = '取消时间';
                                timeRow = `<div class=\"modal-row\"><span class=\"modal-label\">${timeLabel}：</span><span class=\"modal-value\">${formatDate(order.updatedAt)}</span></div>`;
                            }
                            let statusTagClass = 'modal-status-tag';
                            if (statusClass === 'shipped') statusTagClass += ' shipped';
                            if (statusClass === 'completed') statusTagClass += ' completed';
                            if (statusClass === 'cancelled') statusTagClass += ' cancelled';
                            content.innerHTML = `
                                <div class=\"modal-row\"><span class=\"modal-label\">订单ID：</span><span class=\"modal-value\"><strong>${order.id}</strong></span></div>
                                <div class=\"modal-row\"><span class=\"modal-label\">书名：</span><span class=\"modal-value\">${order.bookTitle}</span></div>
                                <div class=\"modal-row\"><span class=\"modal-label\">买家：</span><span class=\"modal-value\">${order.buyerName}</span></div>
                                <div class=\"modal-row\"><span class=\"modal-label\">数量：</span><span class=\"modal-value\">${order.quantity}</span></div>
                                <div class=\"modal-row\"><span class=\"modal-label\">总价：</span><span class=\"modal-value\"><strong>￥${order.totalPrice.toFixed(2)}</strong></span></div>
                                <div class=\"modal-row\"><span class=\"modal-label\">订单状态：</span><span class=\"modal-value\"><span class=\"${statusTagClass}\">${statusText}</span></span></div>
                                <div class=\"modal-row\"><span class=\"modal-label\">下单时间：</span><span class=\"modal-value\">${createdAt}</span></div>
                                ${timeRow}
                            `;
                        } else {
                            content.innerHTML = '<div style="color:#ff6b6b;text-align:center;">加载失败: '+(data.message||'未知错误')+'</div>';
                        }
                    })
                    .catch(() => {
                        content.innerHTML = '<div style="color:#ff6b6b;text-align:center;">网络错误，无法加载订单详情</div>';
                    });
            };
            // 关闭弹窗
            document.getElementById('orderModalClose').onclick = function() {
                document.getElementById('orderModalMask').style.display = 'none';
            };
            document.getElementById('orderModalMask').onclick = function(e) {
                if (e.target === this) this.style.display = 'none';
            };

            // 页面加载时获取订单数据
            loadOrders();
            // 每30秒自动刷新订单数据
            var orderAutoRefreshTimer = setInterval(loadOrders, 30000);
            // 页面卸载时清理定时器
            window.addEventListener('beforeunload', function() { clearInterval(orderAutoRefreshTimer); });
        })();
    </script>
</body>
</html> 